<template>
  <div class="university-explorer">
    <div class="page-header">
      <h2>高校探索</h2>
      <div class="header-tools">
        <el-autocomplete
          v-model="searchKey"
          :fetch-suggestions="querySearch"
          placeholder="搜索学校"
          clearable
          @select="handleSelect"
          class="search-input"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
          <template #default="{ item }">
            <div class="suggestion-item" @click="handleSelect(item)">
              <span>{{ item.name }}</span>
              <span class="suggestion-location">{{ item.location }}</span>
            </div>
          </template>
        </el-autocomplete>
        <el-select v-model="region" placeholder="地区">
          <el-option v-for="item in regions" :key="item" :label="item" :value="item" />
        </el-select>
        <el-select v-model="type" placeholder="学校类型">
          <el-option label="综合类" value="综合" />
          <el-option label="理工类" value="理工" />
          <el-option label="农林类" value="农林" />
          <el-option label="医药类" value="医药" />
          <el-option label="师范类" value="师范" />
          <el-option label="财经类" value="财经" />
        </el-select>
        <el-select v-model="level" placeholder="学校层次">
          <el-option label="985" value="985" />
          <el-option label="211" value="211" />
          <el-option label="双一流" value="双一流" />
        </el-select>
      </div>
    </div>

    <div class="explorer-content">
      <!-- 左侧地图筛选 -->
      <div class="map-filter card">
        <div style="height: 300px; width: 100%">
          <BMap ref="BMapRef" :map-room="4" />
        </div>
        <div class="region-stats">
          <h3>地区统计</h3>
          <div class="stats-list">
            <div v-for="stat in regionStats" :key="stat.region" class="stat-item">
              <span>{{ stat.region }}</span>
              <span>{{ stat.count }}所</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧内容区 -->
      <div class="right-content">
        <!-- 数据概览卡片 -->
        <div class="overview-cards">
          <el-row :gutter="20">
            <el-col :span="6" v-for="card in overviewCards" :key="card.title">
              <el-card shadow="hover" class="overview-card">
                <div class="card-content">
                  <el-icon class="card-icon" :class="card.type">
                    <component :is="card.icon" />
                  </el-icon>
                  <div class="card-info">
                    <div class="card-value">{{ card.value }}</div>
                    <div class="card-title">{{ card.title }}</div>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>

        <!-- 学校列表和图表 -->
        <div class="university-list card">
          <div class="list-header">
            <h3>高校列表</h3>
            <el-radio-group v-model="listView" size="small">
              <el-radio-button label="table">表格</el-radio-button>
              <el-radio-button label="card">卡片</el-radio-button>
            </el-radio-group>
          </div>

          <div v-if="listView === 'table'" class="table-container">
            <!-- 表格视图 -->
            <el-table
              :data="paginatedUniversityList"
              style="width: 100%"
              height="calc(100% - 100px)"
              v-loading="loading"
            >
              <el-table-column prop="name" label="学校名称" min-width="120">
                <template #default="{ row }">
                  <div class="university-name">
                    <span>{{ row.name }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="type" label="类型" min-width="150" />
              <el-table-column prop="province" label="省份" min-width="90" />
              <el-table-column prop="level" label="层次" min-width="120">
                <template #default="{ row }">
                  <el-tag
                    v-if="row.level"
                    :type="row.level === '985' ? 'danger' : row.level === '211' ? 'warning' : 'info'"
                  >
                    {{ row.level }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="score" label="综合评分" min-width="120">
                <template #default="{ row }">
                  <el-rate v-model="row.score" disabled show-score text-color="#ff9900" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150" fixed="right">
                <template #default="{ row }">
                  <el-button type="primary" link @click="showUniversityDetail(row)">查看详情</el-button>
                  <el-button type="success" link @click="compareUniversity(row)">对比</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="filteredUniversityList.length"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </div>

          <!-- 卡片视图 -->
          <div v-else class="university-cards">
            <el-row :gutter="20">
              <el-col :span="8" v-for="university in filteredUniversityList" :key="university.name">
                <el-card class="university-card" shadow="hover">
                  <div class="university-card-header">
                    <div class="university-info">
                      <h4>{{ university.name }}</h4>
                      <div class="university-tags">
                        <el-tag
                          size="small"
                          :type="
                            university.level === '985' ? 'danger' : university.level === '211' ? 'warning' : 'info'
                          "
                        >
                          {{ university.level }}
                        </el-tag>
                        <el-tag size="small" type="success">{{ university.type }}</el-tag>
                      </div>
                    </div>
                  </div>
                  <div class="university-card-content">
                    <div class="info-item">
                      <el-icon><Location /></el-icon>
                      <span>{{ university.province }}</span>
                    </div>
                    <div class="info-item">
                      <el-icon><Star /></el-icon>
                      <el-rate v-model="university.score" disabled show-score text-color="#ff9900" />
                    </div>
                  </div>
                  <div class="university-card-footer">
                    <el-button type="primary" link @click="showUniversityDetail(university)">查看详情</el-button>
                    <el-button type="success" link @click="compareUniversity(university)">对比</el-button>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </div>
      </div>
    </div>

    <!-- 学校详情弹窗 -->
    <el-dialog v-model="dialogVisible" title="学校详情" width="70%">
      <div class="university-detail">
        <div class="detail-header">
          <div class="university-basic">
            <div class="basic-info">
              <h2>{{ currentUniversity.name }}</h2>
              <p>{{ currentUniversity.type }} | {{ currentUniversity.province }}</p>
            </div>
          </div>
          <div class="university-scores">
            <div class="score-item">
              <div class="score-value">{{ currentUniversity.score }}</div>
              <div class="score-label">综合评分</div>
            </div>
            <div class="score-item">
              <div class="score-value">{{ currentUniversity.employmentRate }}%</div>
              <div class="score-label">就业率</div>
            </div>
            <div class="score-item">
              <div class="score-value">{{ currentUniversity.researchScore }}</div>
              <div class="score-label">科研实力</div>
            </div>
          </div>
        </div>

        <!-- 专业设置 -->
        <div class="majors">
          <h3>开设专业</h3>
          <div class="major-categories">
            <el-collapse v-model="activeCategories">
              <el-collapse-item
                v-for="category in majorCategories"
                :key="category.name"
                :title="category.name"
                :name="category.name"
              >
                <div class="major-grid">
                  <div v-for="major in category.majors" :key="major.name" class="major-item">
                    <el-tooltip :content="major.description" placement="top">
                      <div class="major-content">
                        <span class="major-name">{{ major.name }}</span>
                        <el-tag
                          size="small"
                          :type="major.level === 'A+' ? 'danger' : major.level === 'A' ? 'warning' : 'info'"
                        >
                          {{ major.level }}
                        </el-tag>
                      </div>
                    </el-tooltip>
                  </div>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
        </div>

        <!-- 就业统计 -->
        <div class="employment-stats">
          <h3>就业统计</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <ECharts :options="employmentOptions" height="300px" />
            </el-col>
            <el-col :span="12">
              <ECharts :options="salaryOptions" height="300px" />
            </el-col>
          </el-row>
        </div>

        <!-- 科研实力 -->
        <div class="research-stats">
          <h3>科研实力</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <ECharts :options="researchOptions" height="300px" />
            </el-col>
            <el-col :span="12">
              <ECharts :options="patentOptions" height="300px" />
            </el-col>
          </el-row>
        </div>
      </div>
    </el-dialog>

    <!-- 学校对比弹窗 -->
    <el-dialog v-model="compareDialogVisible" title="学校对比" width="80%">
      <div class="university-compare">
        <el-table :data="compareData" style="width: 100%">
          <el-table-column prop="item" label="对比项" width="180" />
          <el-table-column :label="compareUniversities[0]?.name" min-width="200">
            <template #default="{ row }">
              <div class="compare-value">{{ row.value1 }}</div>
            </template>
          </el-table-column>
          <el-table-column :label="compareUniversities[1]?.name" min-width="200">
            <template #default="{ row }">
              <div class="compare-value">{{ row.value2 }}</div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue"
import { Search, Location, Star } from "@element-plus/icons-vue"
import { ElMessage } from "element-plus"
import { BMap } from "@/components"
import type { UniversityInfo, MajorCategory } from "@/types/university"
import type { SearchSuggestion } from "@/types/search"
import collegesInfo from "@/assets/colleges-info.json"

// 搜索和筛选条件
const searchKey = ref("")
const region = ref("")
const type = ref("")
const level = ref("")
const listView = ref("table")
const focusLocation = ref<{ name: string; lng: number; lat: number } | undefined>()
const selectedProvinces = ref<string[]>([])
const loading = ref(false)

// 地图
const BMapRef = ref<any>()

// 分页相关
const currentPage = ref(1)
const pageSize = ref(20)

// 地区选项
const regions = ["华东", "华北", "华中", "华南", "西南", "西北", "东北"]

// 缓存地区映射
const regionMap: Record<string, string[]> = {
  华东: ["上海", "江苏", "浙江", "安徽", "福建", "江西", "山东"],
  华北: ["北京", "天津", "河北", "山西", "内蒙古"],
  华中: ["河南", "湖北", "湖南"],
  华南: ["广东", "广西", "海南"],
  西南: ["重庆", "四川", "贵州", "云南", "西藏"],
  西北: ["陕西", "甘肃", "青海", "宁夏", "新疆"],
  东北: ["辽宁", "吉林", "黑龙江"]
}

// 数据概览卡片
const overviewCards = computed(() => [
  {
    title: "高校总数",
    value: collegesInfo.length.toString(),
    icon: "School",
    type: "primary"
  },
  {
    title: "985高校",
    value: collegesInfo.filter(college => college.school_type.includes("985")).length.toString(),
    icon: "Trophy",
    type: "success"
  },
  {
    title: "211高校",
    value: collegesInfo.filter(college => college.school_type.includes("211")).length.toString(),
    icon: "Medal",
    type: "warning"
  },
  {
    title: "双一流高校",
    value: collegesInfo.filter(college => college.school_type.includes("双一流")).length.toString(),
    icon: "User",
    type: "info"
  }
])

// 地区统计数据
const regionStats = computed(() => {
  return regions.map(region => {
    const provinces = regionMap[region] || []
    const count = collegesInfo.filter(college => provinces.includes(college.location)).length
    return { region, count }
  })
})

// 过滤后的大学列表
const filteredUniversityList = computed(() => {
  loading.value = true
  let filteredList = [...collegesInfo]

  // 应用搜索过滤
  if (searchKey.value) {
    filteredList = filteredList.filter(college => college.name.includes(searchKey.value))
  }

  // 应用地区过滤
  if (region.value) {
    const provinces = regionMap[region.value] || []
    filteredList = filteredList.filter(college => provinces.includes(college.location))
  }

  // 应用类型过滤
  if (type.value) {
    filteredList = filteredList.filter(college => college.type === type.value)
  }

  // 应用层次过滤
  if (level.value) {
    filteredList = filteredList.filter(college => college.school_type.includes(level.value))
  }

  loading.value = false
  return filteredList.map(college => ({
    name: college.name,
    type: college.type,
    province: college.location,
    level: college.school_type,
    score: parseFloat(college.score) / 200
  }))
})

// 分页后的大学列表
const paginatedUniversityList = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredUniversityList.value.slice(start, end)
})

// 监听筛选条件变化，重置页码
watch([searchKey, region, type, level], () => {
  currentPage.value = 1
})

// 处理分页大小变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
}

// 处理页码变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val
}

// 弹窗控制
const dialogVisible = ref(false)
const compareDialogVisible = ref(false)
const currentUniversity = ref<UniversityInfo>({} as UniversityInfo)
const compareUniversities = ref<UniversityInfo[]>([])

// 专业类别展开控制
const activeCategories = ref<string[]>([])
const majorCategories = ref<MajorCategory[]>([
  {
    name: "工学",
    majors: [
      {
        name: "计算机科学与技术",
        level: "A+",
        description: "计算机科学与技术专业培养具有扎实的计算机理论基础和专业技能的人才"
      },
      { name: "软件工程", level: "A", description: "软件工程专业培养具有软件开发和项目管理能力的人才" }
    ]
  }
  // ... 其他学科类别
])

// 就业统计图表配置
const employmentOptions = computed(() => ({
  title: {
    text: "近年就业情况"
  },
  tooltip: {},
  xAxis: {
    data: ["2019", "2020", "2021", "2022"]
  },
  yAxis: {},
  series: [
    {
      name: "就业率",
      type: "bar",
      data: [95, 93, 94, 96]
    }
  ]
}))

// 薪资分布图表配置
const salaryOptions = computed(() => ({
  title: {
    text: "毕业生薪资分布"
  },
  tooltip: {},
  series: [
    {
      name: "薪资分布",
      type: "pie",
      radius: "50%",
      data: [
        { value: 35, name: "10k-15k" },
        { value: 30, name: "15k-20k" },
        { value: 20, name: "20k-25k" },
        { value: 15, name: "25k以上" }
      ]
    }
  ]
}))

// 科研实力图表配置
const researchOptions = computed(() => ({
  title: {
    text: "科研项目数量"
  },
  tooltip: {},
  xAxis: {
    data: ["2019", "2020", "2021", "2022"]
  },
  yAxis: {},
  series: [
    {
      name: "项目数",
      type: "line",
      data: [120, 150, 180, 200]
    }
  ]
}))

// 专利数量图表配置
const patentOptions = computed(() => ({
  title: {
    text: "专利授权数量"
  },
  tooltip: {},
  xAxis: {
    data: ["2019", "2020", "2021", "2022"]
  },
  yAxis: {},
  series: [
    {
      name: "专利数",
      type: "bar",
      data: [80, 100, 120, 150]
    }
  ]
}))

// 对比数据
const compareData = computed(() => [
  { item: "学校名称", value1: compareUniversities.value[0]?.name, value2: compareUniversities.value[1]?.name },
  { item: "学校类型", value1: compareUniversities.value[0]?.type, value2: compareUniversities.value[1]?.type },
  { item: "所在地区", value1: compareUniversities.value[0]?.province, value2: compareUniversities.value[1]?.province },
  { item: "学校层次", value1: compareUniversities.value[0]?.level, value2: compareUniversities.value[1]?.level },
  { item: "综合评分", value1: compareUniversities.value[0]?.score, value2: compareUniversities.value[1]?.score }
])

// 搜索建议方法
const querySearch = (queryString: string, cb: (arg: SearchSuggestion[]) => void) => {
  const results = queryString
    ? collegesInfo
        .filter(item => item.name.includes(queryString))
        .map(item => ({
          name: item.name,
          lng: item.lng,
          lat: item.lat,
          type: "college"
        }))
    : []

  cb(results as SearchSuggestion[])
}

// 处理搜索选择
const handleSelect = (item: SearchSuggestion) => {
  console.log(item)
  if (item.type === "college") {
    searchKey.value = item.name
    focusLocation.value = {
      name: item.name,
      lng: item.lng,
      lat: item.lat
    }
  }
}

watch(
  () => focusLocation.value,
  newVal => {
    if (newVal && BMapRef.value) {
      console.log(newVal)
      BMapRef.value.setMapCenter(newVal)
    }
  }
)

// 处理地图区域点击
const handleRegionClick = (regionName: string) => {
  region.value = regionName
  selectedProvinces.value = [regionName]
}

// 显示大学详情
const showUniversityDetail = (university: UniversityInfo) => {
  const college = collegesInfo.find(c => c.name === university.name)
  if (college) {
    currentUniversity.value = {
      ...university,
      introduce: college.introduce,
      employmentRate: 95, // 这里需要从实际数据中获取
      researchScore: parseFloat(college.score) / 200
    }
    dialogVisible.value = true
  }
}

// 对比大学
const compareUniversity = (university: UniversityInfo) => {
  if (compareUniversities.value.length >= 2) {
    ElMessage.warning("最多只能对比两所大学")
    return
  }
  compareUniversities.value.push(university)
  if (compareUniversities.value.length === 2) {
    compareDialogVisible.value = true
  }
}
</script>

<style lang="scss" scoped>
.university-explorer {
  height: 100%;
  width: 100%;
  background: #f5f7fa;

  .page-header {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: var(--header-height);

    h2 {
      margin: 0;
      font-size: 24px;
      color: #303133;
    }

    .header-tools {
      display: flex;
      gap: 12px;

      .search-input {
        width: 300px;
      }

      .el-select {
        width: 160px;
      }
    }
  }

  .explorer-content {
    display: grid;
    grid-template-columns: 1fr 1.5fr;
    gap: 20px;
    height: calc(100% - var(--header-height) - 20px);
    overflow: hidden;
    width: 100%;

    .card {
      background: #fff;
      border-radius: 8px;
      padding: 20px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }

    .map-filter {
      .region-stats {
        margin-top: 20px;

        h3 {
          margin-bottom: 16px;
          color: #303133;
        }

        .stats-list {
          display: grid;
          grid-template-columns: repeat(3, 1fr);
          gap: 12px;

          .stat-item {
            display: flex;
            justify-content: space-between;
            padding: 8px;
            background: #f5f7fa;
            border-radius: 4px;
            color: #606266;
          }
        }
      }
    }

    .right-content {
      height: 100%;
      overflow: hidden;
      display: flex;
      flex-direction: column;
      gap: 20px;

      .overview-cards {
        .overview-card {
          .card-content {
            display: flex;
            align-items: center;
            gap: 16px;

            .card-icon {
              font-size: 48px;
              padding: 16px;
              border-radius: 8px;

              &.primary {
                color: #409eff;
                background: #ecf5ff;
              }

              &.success {
                color: #67c23a;
                background: #f0f9eb;
              }

              &.warning {
                color: #e6a23c;
                background: #fdf6ec;
              }

              &.info {
                color: #909399;
                background: #f4f4f5;
              }
            }

            .card-info {
              .card-value {
                font-size: 24px;
                font-weight: bold;
                color: #303133;
                margin-bottom: 4px;
              }

              .card-title {
                font-size: 14px;
                color: #909399;
              }
            }
          }
        }
      }

      .university-list {
        flex: 1;
        overflow: hidden;

        .list-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16px;

          h3 {
            margin: 0;
            color: #303133;
          }
        }

        .table-container {
          height: 100%;
          overflow: hidden;
          display: flex;
          flex-direction: column;

          .pagination-container {
            margin-top: 16px;
            display: flex;
            justify-content: flex-end;
          }
        }

        .university-cards {
          height: calc(100% - 50px);
          overflow-y: auto;

          .university-card {
            margin-bottom: 20px;

            .university-card-header {
              display: flex;
              align-items: center;
              gap: 16px;
              margin-bottom: 16px;

              .university-info {
                h4 {
                  margin: 0 0 8px 0;
                  color: #303133;
                }

                .university-tags {
                  display: flex;
                  gap: 8px;
                }
              }
            }

            .university-card-content {
              .info-item {
                display: flex;
                align-items: center;
                gap: 8px;
                margin-bottom: 8px;
                color: #606266;
              }
            }

            .university-card-footer {
              display: flex;
              justify-content: flex-end;
              gap: 12px;
              margin-top: 16px;
            }
          }
        }
      }
    }
  }

  .university-detail {
    .detail-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24px;

      .university-basic {
        display: flex;
        align-items: center;
        gap: 16px;

        .basic-info {
          h2 {
            margin: 0 0 8px 0;
            color: #303133;
          }

          p {
            margin: 0;
            color: #909399;
          }
        }
      }

      .university-scores {
        display: flex;
        gap: 32px;

        .score-item {
          text-align: center;

          .score-value {
            font-size: 24px;
            font-weight: bold;
            color: #303133;
            margin-bottom: 4px;
          }

          .score-label {
            font-size: 14px;
            color: #909399;
          }
        }
      }
    }

    .majors {
      margin-bottom: 32px;

      h3 {
        margin-bottom: 16px;
        color: #303133;
      }

      .major-grid {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        gap: 12px;

        .major-item {
          .major-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 12px;
            background: #f5f7fa;
            border-radius: 4px;
            cursor: pointer;

            &:hover {
              background: #ecf5ff;
            }

            .major-name {
              color: #606266;
            }
          }
        }
      }
    }

    .employment-stats,
    .research-stats {
      margin-bottom: 32px;

      h3 {
        margin-bottom: 16px;
        color: #303133;
      }
    }
  }

  .university-compare {
    .compare-value {
      padding: 8px;
      background: #f5f7fa;
      border-radius: 4px;
      color: #606266;
    }
  }
}

:deep(.el-autocomplete-suggestion) {
  .suggestion-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 12px;

    .suggestion-location {
      color: #909399;
      font-size: 13px;
    }
  }
}
</style>
